import axios from 'axios'
import { router } from '../main'

//创建axios实例
const service = axios.create({
    baseURL: process.env.VUE_APP_PATH,
    timeout: 10000, //超时时间
});
// service.defaults.retry=1;
// service.defaults.retryDelay=1000;
//添加request拦截器
service.interceptors.request.use(config => {
    return config;
}, error => {
    Promise.reject(error);
});
let refreshTokenState=true;//用于控制刷新token的状态
//添加response拦截器
service.interceptors.response.use(
    response => {
        let res = {};
        res.headers=response.headers;
        res.status = response.status;
        res.data = response.data;
        return res;

    },
    error => {
        if(error.response){
            //网络延迟或者账号在别处登录时，重新返回登录页，重新登录
            if (error.response.status == 401) {
                //跳转到xx页面
                console.log('执行401时token过期或账号挤退，通知丰飞 显示弹框 提示重新登录');
				if (!!window.native && !!window.native.sendMessage && typeof (window.native.sendMessage) == 'function') {
					var json = {
						"action": "tokenExpired",
						"callback": "nativeCallback",
						"data": {

						}
					};
					window.native.sendMessage(JSON.stringify(json))
				}
            }
            return Promise.reject(error.response);
        }else {
            //超时处理
            let config = error.config;
            if(error.code=="ECONNABORTED"&&error.message.indexOf('timeout')!=-1){
                console.log("网络超时,正在重试中。。。");
                if(config.data!=""){
                    config.data=JSON.parse(localStorage.getItem("httpData"));
                }
                return axios.request(config);
            }
        }
    }
);

//封装get接口
// params={} 是设置默认值
export function get(url, params = {}) {
    // params.t = new Date().getTime(); //get方法加一个时间参数,解决ie下可能缓存问题.
    return service({
        url: url,
        method: 'get',
        headers: {
            'Content-Type':'application/json;charset=utf-8',
            "Authorization":localStorage.getItem("userAuth")
        },
        // params
    })
}

//封装post请求
export function post(url, data = {},timeout) {
    //默认配置
    let sendObject = {
        url: url,
        method: "post",
        headers: {
            'Content-Type': 'application/json;charset=utf-8',
            // "X-Requested-With":'XMLHttpRequest',
            // "Cache-Control":'no-cache',
            // "token":localStorage.getItem("token"),
            // 'x-sf-userid':'80004886'
        },
        data: data
    };

    if(timeout){
        sendObject.timeout=timeout;
    }
    sendObject.data = JSON.stringify(data);
    return service(sendObject)
}

//封装put方法 (resfulAPI常用)
function put(url, data = {}) {
    return service({
        url: url,
        method: 'put',
        headers: {
            'Content-Type': 'application/json;charset=UTF-8'
        },
        data: JSON.stringify(data)
    })
}

//删除方法(resfulAPI常用)
function deletes(url) {
    return service({
        url: url,
        method: 'delete',
        headers: {}
    })
}

//patch方法(resfulAPI常用)
function patch(url) {
    return service({
        url: url,
        method: 'patch',
        headers: {}
    })
}

//处理格式化URL（/demo/{id}）
function render(url, data) {
    var re = /{([^]+)?}/;
    var match = '';
    while ((match = re.exec(url))) {
        url = url.replace(match[0], data[match[1]])
    }
    return url
}

const fetch = (options) => {
    // console.log('******:',process.env);
    // console.log('******:',process.env.VUE_APP_PATH);

    let timeout="";

    // let url=window.location.origin+options.url;

	let env=localStorage.env;
	let path='http://10.88.5.99:8888';
	// let	path='http://10.88.5.179:8088';
    if(env=='prod'){
		path='https://sfa-wgw.sf-airlines.com:8443'; //prod
    } else if(env=='sit'){
		path='http://sfa-wgw.sit.sf-airlines.com:8000'
    }
    // else if(env=='dev'){
    //     // path='http://10.88.5.99:8886';
		// path='http://10.88.5.179:8088';
    // }
    // let url=process.env.VUE_APP_PATH+options.url;
    let url=path+options.url;

    url = render(url, options.data);
    switch (options.method.toUpperCase()) {
        case 'GET':
            return get(url, options.data);
        case 'POST':
            return post(url, options.data,timeout);
        case 'PUT':
            return put(url, options.data);
        case 'DELETE':
            return deletes(url, options.data);
        case 'PATCH':
            return patch(url, options.data);
        default:
            return service(options)
    }
};

/**
 * 提供一个http方法
 * url 访问路径 不包括域名和项目名
 * data 参数对象
 * method 请求方式
 *  */
export function http(url = '', data = {}, method = "GET",sign='') {
    // localStorage.setItem("httpData",JSON.stringify(data));
    const options = { url: url, data: data, method: method ,sign:sign};
    return fetch(options).catch(error => {
        throw error
    })
}